<template>
    <div style="width: 100%;height:100%;">
        <bpm-header :title="bpmInst.subject" :user="bpmInst.createBy"></bpm-header>
        <div class="bpm-task-content">
            <a-tabs class="rx-a-tabs" default-active-key="details" @change="changeTabs($event)">
                <div slot="tabBarExtraContent" class="tabs-toolbar">
                    <bpm-detail-buttons :buttons="buttons" :curVm="getCurVm()"></bpm-detail-buttons>
                </div>
                <a-tab-pane key="details" :tab="i18n('list.detail', '详情')">
                    <div class="tab-center-bg">
                        <div class="tab-center-content" :class="{'tab-center-content-show':show}">
                            <div class="tab-center">
                                <bpm-inst-info :bpmInst="bpmInst"  :showStatus="showStatus" :status="status"/>
                                <div style="padding:0 10px 10px;">
                                    <rx-forms ref="rxForms" v-if="processConfig.formType=='online'"></rx-forms>
                                    <component ref="customForm" :is="formComponent" :pk="pk"
                                               v-else-if="processConfig.formType=='custom'"></component>
                                    <component ref="outSideUrlForm" :is="formComponent"
                                               :pk="pk" :showUrl="outSideUrl" :urlParamData="urlParamData"
                                               v-else-if="urlParamsShow"></component>
                                </div>
                            </div>
                        </div>
                        <div class="bpm-history-button" @click="foldRight">
                            <i class="iconfont iconVue3jpaas-icon_shenpilishi"></i>
                        </div>
                        <div class="bpm-task-history" :class="{'bpm-task-show':show}">
                            <!--审批历史-->
                            <div style="width: 340px;height: 100%;">
                                <div class="bpm-task-history-text">
                                    <span>{{i18n('list.appHistory', '审批历史')}}</span>
                                    <span class="bpm-history-close" @click="foldRight">
                                        <a-icon type="close" />
                                    </span>
                                </div>
                                <bpm-history :inst-id="instId" :historyShow.sync="historyShow"/>
                            </div>

                        </div>
                    </div>
                </a-tab-pane>
                <a-tab-pane key="flowChart" :tab="i18n('list.flowChart', '流程图')" >
                    <bpm-image-view  v-if="isShowImage" :inst-id="instId" :preview="false" :formData="formData"></bpm-image-view>
                </a-tab-pane>
            </a-tabs>
        </div>
        <!-- 流程实例日志 -->
        <bpm-inst-logs :instId="instId" :log-show.sync="logShow"/>
        <!--流程实例消息-->
        <bpm-inst-msgs :instId="instId" :msg-show.sync="msgShow"/>

        <bpm-commu-history :inst-id="instId" :bpmCommuShow.sync="bpmCommuShow"/>
    </div>
</template>

<script>
import {RxDialog, Util, RxFit,App} from '@lowcode/jpaas-common-lib';
import BpmInstMsgs from "./BpmInstMsgs"
import BpmInstLogs from "./BpmInstLogs";
import BpmInstApi from '@/api/bpm/core/bpmInst'
import FormPcApi from "@/api/form/core/formPc";
import BpmImageView from "../comps/BpmImageView";
import RxForms from "./RxForms";
import BpmCheckHistory from "./BpmCheckHistory";
import BpmCommuHistory from "./BpmCommuHistory";
import BpmInstInfo from "./BpmInstInfo";
import formbase from '@/api/formbase';
import BpmInstTransfer from "../core/BpmInstTransfer";
import BpmInstTakeBack from "@/views/modules/bpm/core/BpmInstTakeBack";
import BpmStatus from "@/views/modules/bpm/core/component/BpmStatus";
import BpmInstTrackedApi from "@/api/bpm/core/bpmInstTracked";
import userState from "@/assets/js/userState";
import FlowUtil from "@/views/modules/bpm/js/FlowUtil.js";
import BpmTaskCommuApi from '@/api/bpm/core/bpmTaskCommu'
import {mapState} from 'vuex'
import i18nEdit from '../../i18n/i18nEdit.js'
import BpmDetailButtons from "@/views/modules/bpm/core/component/BpmDetailButtons";
import bpmHeader from "@/views/modules/bpm/core/component/bpmHeader";
import bpmHistory from "@/views/modules/bpm/core/component/bpmHistory";


export default {
    name: "BpmInstDetail",
    components: {
        BpmDetailButtons,
        RxDialog,
        RxFit,bpmHistory,
        RxForms,
        BpmInstMsgs,
        BpmInstLogs,
        BpmCheckHistory,
        BpmCommuHistory,
        BpmInstInfo,
        BpmInstTransfer,
        BpmInstTakeBack,
        BpmStatus,
        bpmHeader,BpmImageView
    },
    mixins: [formbase, userState,FlowUtil,i18nEdit,App],
    props: {
        layerid: {type: String},
        lydata: {type: Object},
        destroy: {type: Function},
        instId: {
            type: String,
            required: true
        },
        backNodeId: {//在流程明细中进行回退时指定的目标节点
            type: String,
            required: false
        },
        allowTransfer: {
            type: Boolean,
            required: false,
            default: false
        },
        allowTransReply: {
            type: Boolean,
            required: false,
            default: false
        },

        //来自页面(mydone:我完成的审批,mystart:我发起的流程)
        from: {
            type: String,
            default: ""
        }
    },
    computed: {

        trackedTheme() {
            return this.bpmInstDetail.tracked == '1' ? 'filled' : 'outlined';
        },
        trackedColor() {
            return this.bpmInstDetail.tracked == '1' ? '#eab207' : '#1890ff';
        },
        trackText() {
            return this.bpmInstDetail.tracked == "1" ? this.i18n('list.tracked','已跟踪') : this.i18n('list.track','跟踪');
        },
        canTrack() {
            return this.bpmInst.status == "RUNNING" || this.bpmInst.status == 'REVOKE';
        },
        showStatus() {
            if (!this.processConfig.switchOptions) {
                return true;
            }
            let rtn = this.processConfig.switchOptions.includes("showStatus");
            return rtn;

        },
        showMsgBtn(){
            let ary=['ARCHIVED'];
            if(ary.includes(this.status)){
                return false;
            }
            return true;
        }
    },
    data() {
        return {
            historyShow: false,
            bpmCommuBtnShow: false,
            bpmCommuShow: false,
            logShow: false,
            msgShow: false,
            bpmInstDetail: {},
            bpmInst: {},
            status: "",
            processConfig: {
                buttons: [],
                startConfirm: false,
                fillOpinion: false,
                assignFlowUsers: false,
                startCalFlowusers: false,
                //是否允许选择路径。
                allowSelectPath: false,

                formType: "online",
                //开关
                switchOptions: []
            },
            buttons: [],
            pkId: "",
            formComponent: "",
            outSideUrl:"",
            urlParamData:[],
            urlParamsShow:false,
            pk: "",
            backBtnLoading: false,//撤回按钮加载状态
            //根实例
            rootVm: true,
            //是否可以撤回
            canRevoke: false,
            myStartBtn:[],
            //按钮loading
            btnLoading:false,
            show:true,
            formData:{},
            isShowImage:false
        }
    },
    created() {
        this.loadDetail();
        this.getCommuData();
    },
    methods: {
        changeTabs(key){
            if(key=='flowChart'){
                this.getFormData();
            }else {
                this.isShowImage=false;
            }
        },
        getFormData(){
            if (this.processConfig.formType == "custom") {
                this.formData = this.$refs.customForm.getData();
            }else if (this.processConfig.formType == "outsideUrl") {
                this.formData = this.$refs.outSideUrlForm.getData();
            } else {
                this.formData = this.$refs.rxForms.getData();
            }
            this.isShowImage=true;
        },
        foldRight(){
            this.show = !this.show
        },
        i18n(name,text,key){
            return this.$ti18(name,text,"bpmInst",key);
        },
        getCommuData() {
            if (!this.instId) {
                return;
            }
            let parameter = {
                instId: this.instId,
                taskId: "",
                nodeId: ""
            }
            BpmTaskCommuApi.getAllCommus(parameter).then(res => {
                if (!res.success) {
                    return;
                }
                let dataList = res.data;
                if(dataList.length>0){
                    this.bpmCommuBtnShow=true;
                }
            });
        },
        isBuildinBtn(btn) {
            var btns = ['btnTransfer', 'btnTransReply', 'btnBack', 'btnMessage','doDiscard', 'delInst','restoreInst','supspendInst'];
            return btns.indexOf(btn) > -1;
        },
        showCheckHistory() {
            this.historyShow = true;
        },
        doCommuHistory() {
            this.bpmCommuShow = true;
        },
        showBpmInstLog() {
            this.logShow = true;
        },
        showMsg() {
            this.msgShow = true;
        },
        retrieveTaskNode() {
            let self_ = this;
            Util.open({
                component: BpmInstTakeBack,
                curVm: this,
                widthHeight: ['600px', '320px'],
                title: self_.i18n('list.withdraw','撤回流程'),
                data: {
                    bpmInst: this.bpmInst,
                    from: this.from
                }
            }, function (action) {
                self_.loadDetail();
            });

        },
        //显示流程图
        showProcessImg() {
            Util.open({
                component: BpmImageView,
                curVm: this,
                widthHeight: ['1024px', '600px'],
                title: this.i18n('list.flowChart','流程图'),
                data: {
                    instId: this.instId,
                    formData: this.getFormData(),
                    preview: false
                }
            }, function (action) {
            });
        },
        loadDetail() {
            let self = this;
            if (!this.instId) {
                this.instId = this.$route.params.instId;
            }
            var self_ = this;
            BpmInstApi.getInstDetail(this.instId, this.from).then(res => {
                this.bpmInstDetail = res;
                this.bpmInst = res.bpmInst;
                var contextData = {
                    type: "detail",
                    instNo: res.bpmInst.instNo,
                    subject: res.bpmInst.subject,
                    instId: self.instId,
                    opinionHistorys: res.bpmCheckHistories
                };
                var config = Util.deepClone(self_.processConfig);
                self_.processConfig = Object.assign(config, res.processConfig);
                self_.buttons = self_.processConfig.buttonDetailConfigs;
                self_.canRevoke = res.canRevoke;
                self_.status = res.bpmInst.status;
                self.pkId = res.bpmInst.busKey;
                self.handFormConfig(res.processConfig, res.bpmInst);
                self.$refs.rxForms.setData(res.formData.data, true, contextData);
                //暂停/恢复按钮
                if(self_.buttons && self_.buttons.length>0){
                    if(this.bpmInstDetail.bpmInst.status=="RUNNING"){
                        this.myStartBtn=['doDiscard', 'delInst','supspendInst'];
                    }else if(this.bpmInstDetail.bpmInst.status=="SUPSPEND") {
                        this.myStartBtn=['doDiscard', 'delInst','restoreInst'];
                    }else if(this.bpmInstDetail.bpmInst.status=="CANCEL") {
                        this.myStartBtn=['delInst'];
                    }
                }
            })
        },
        printForm() {
            var baseUrl = process.env.VUE_APP_ADMIN_FRONT;
            var appId=this.bpmInst.appId;
            var defId = this.bpmInst.defId;
            var instId = this.bpmInst.instId;
            var url = baseUrl ;
            url+="/flowprint/" + defId;
            if (instId) {
                url += "/" + instId;
            } else {
                url += "/-1";
            }
            if(appId){
                url+="?appId=" + appId;
            }
            window.open(url);
        },
        loadUrlView()  {
            // 路由懒加载
            return require('@/layouts/UrlView.vue').default;
        },
        getFormPc(formId){
            var self_=this;
            if(!formId){
                self_.urlParamsShow=true;
                return;
            }
            FormPcApi.get(formId).then(res =>{
                if(!res.success){
                    self_.$message.error(self_.i18n('URLFail','获取外部URL表单失败：')+res.message);
                    return;
                }
                let data =res.data;
                if(data.urlParams){
                    self_.replaceUrlParmaVal(data.urlParams);
                }
                self_.urlParamsShow=true;
                return;
            });
        },
        replaceUrlParmaVal(urlParams){
            var curUser=this.user;
            var contextData={
                userId:curUser.userId,
                defId:this.bpmInst.defId,
                instId:this.instId,
                taskId:"",
                nodeId:""
            }
            var urlParamData=JSON.parse(urlParams);
            for(let i=0;i<urlParamData.length;i++){
                let param=urlParamData[i];
                if(param.paramType){
                    let val = contextData[param.paramKeyVal];
                    param.paramKeyVal=val;
                }
            }
            this.urlParamData=urlParamData;
        },
        loadView(view) { // 路由懒加载
            return () => import(`@/views/${view}`);
        },
        //处理表单配置。
        handFormConfig(conf, bpmInst) {
            var config = Util.deepClone(this.processConfig);
            this.processConfig = Object.assign(config, conf);
            if (!this.processConfig.formType) {
                this.processConfig.formType = "online"
            }
            //获取明细
            if(conf.detailForm.formpc && conf.detailForm.formpc.length > 0){
                var form = conf.detailForm.formpc[0];
                if (form && form.type == "custom") {
                    this.pk = bpmInst.busKey;
                    this.processConfig.formType = "custom";
                    this.formComponent = this.loadView(form.component);
                    return;
                }
                if(form && form.type=="outsideUrl"){
                    this.pk = bpmInst.busKey;
                    this.outSideUrl=form.component;
                    this.processConfig.formType="outsideUrl";
                    this.formComponent=this.loadUrlView();
                    this.getFormPc(form.id);
                    return;
                }
            }
            //获取全局。
            if (conf.globalForm.formpc && conf.globalForm.formpc.length > 0) {
                var form = conf.globalForm.formpc[0];
                if (form && form.type == "custom") {
                    this.pk = bpmInst.busKey;
                    this.processConfig.formType = "custom";
                    this.formComponent = this.loadView(form.component);
                    return;
                }
                if(form && form.type=="outsideUrl"){
                    this.pk = bpmInst.busKey;
                    this.outSideUrl=form.component;
                    this.processConfig.formType="outsideUrl";
                    this.formComponent=this.loadUrlView();
                    this.getFormPc(form.id);
                    return;
                }
            }
        },
        Ureport(name) {
            if (!this.pkId) {
                this.$message.warning(this.i18n('illegal','非法操作'));
                return;
            }
            var url = "/ureport/preview?_u=qiaolin-" + name + "&Id=" + this.pkId;
            window.open(url);
        },
        formPrint() {
            this.printForm();
        },
        close() {
            if (this.destroy) {
                Util.close(this, "cancel");
            } else {
                window.close();
            }
        },

        transferTo() {
            Util.open({
                component: BpmInstTransfer,
                curVm: this,
                widthHeight: ['800px', '500px'],
                title: this.i18n('forwardInst','转发流程实例') + this.bpmInst.subject,
                data: {
                    instId: this.instId,
                    send: true
                },
            }, function (action) {
                console.log(action)
            })
        },
        transferReply() {
            Util.open({
                component: BpmInstTransfer,
                curVm: this,
                widthHeight: ['800px', '500px'],
                title: this.i18n('replyFor','回复转发[') + this.bpmInst.subject + "]",
                data: {
                    instId: this.instId,
                    send: false
                },
            }, function (action) {
                console.log(action)
            })
        },
        doTracked() {
            let instId = this.bpmInst.instId;
            BpmInstTrackedApi.doTracked(instId).then(res => {
                this.bpmInstDetail.tracked = res.data;
            })
        },
        //我发起的流程 按钮
        isMyStartBtn(btn) {
            return this.from=='mystart' && this.myStartBtn.indexOf(btn) > -1;
        },
        //作废
        doDiscard(btn){
            let self_ = this;
            self_.btnLoading=true;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips','操作提示'),
                content: this.i18n('content.cancel','您确定需要作废当前流程吗？'),
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    BpmInstApi.cancelProcess(self_.instId,"作废").then(resp=> {
                        window.location.reload();
                    });
                },
                onCancel() {
                    self_.btnLoading=false;
                }
            })
        },
        //删除
        delInst(btn){
            let self_ = this;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips','操作提示'),
                content: this.$ti18('rxMsa.delInfo','您确定需要删除选中的记录吗？'),
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    BpmInstApi.delBpmInst({ ids: self_.instId }).then(res => {
                        window.close();
                    })
                },
                onCancel() {}
            })
        },
        //恢复
        restoreInst(btn){
            let self_ = this;
            self_.btnLoading=true;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips','操作提示'),
                content: this.i18n('content.restore','您确定需要恢复当前流程吗？'),
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    BpmInstApi.updateProcessStatus(self_.instId,'RUNNING').then(resp=> {
                        window.location.reload();
                    });
                },
                onCancel() {
                    self_.btnLoading=false;
                }
            })
        },
        //暂停
        supspendInst(btn){
            let self_ = this;
            self_.btnLoading=true;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips','操作提示'),
                content: this.i18n('content.suspend','您确定暂停当前流程吗？'),
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    BpmInstApi.updateProcessStatus(self_.instId,'SUPSPEND').then(resp=> {
                        self_.btnLoading=true;
                        window.location.reload();
                    });
                },
                onCancel() {
                    self_.btnLoading=false;
                }
            })
        },
        getCurVm(){
            return this;
        }
    }
}
</script>

<style scoped>
.tab-center-bg{
    width: 100%;
    height: 100%;
    background: #fff;
    overflow: auto;
    position: relative;
}
.tabs-toolbar{
    height: 45px;
    display: flex;
    align-items: center;
}
.tab-center-content{
    display: inline-block;
    vertical-align: top;
    width: 100%;
    padding-bottom: 10px;
    height: calc( 100vh - 109px );
    background: #F5F5F5;
    transition: all .5s;
    overflow: auto;
}
.tab-center-content-show{
    width: calc( 100% - 340px );
}

.tab-center{
    box-sizing: border-box;
    max-width: 1300px;
    width: 80%;
    margin: auto;
    min-height: calc( 100vh - 121px );
    background: #fff;
}
.bpm-task-history{
    vertical-align: top;
    display: inline-block;
    background-color: #fff;
    width: 0;
    opacity: 0;
    transition: all .5s;
    min-height: 100%;
    overflow: hidden;
    position: relative;
    z-index: 11;
}
.bpm-history-button{
    top: 10px;
    right: 10px;
    position: absolute;
    width: 44px;
    height: 44px;
    background: #fff;
    box-shadow: 0 3px 10px 1px rgba(0,0,0,0.06);
    border-radius: 4px;
    z-index: 9;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}
.bpm-task-history-text{
    padding: 10px ;
    border-bottom: 1px solid #E8E8E8;
    font-size: 16px;
    color: #333;
    font-weight: bold;
    display: flex;
    justify-content: space-between;
}
.bpm-history-close{
    display: inline-block;
    padding:0 4px;
    cursor: pointer;
}
.bpm-history-close:hover{
    color: #4d9eff;
}
.bpm-task-show{
    width:340px ;
    opacity: 1;
}

.rx-a-tabs >>> .ant-tabs-bar.ant-tabs-top-bar{
    margin-bottom: 0!important;
}
.bpm-task-content{
    height: calc( 100% - 64px);
}
.rx-a-tabs{
    width: 100%;
    height: 100%;
}

.fitContainer {
    background: #fff;
    padding: 10px;
    padding-right: 0;
    box-sizing: border-box;
    height: 100%;
    width: 100%;
    overflow: auto;
}

.fitContainer .contents {
    background: #fff;
    border-radius: 6px;
    min-height: 100%;
    box-sizing: border-box;
    display: inline-block;
    width: 100%;
    max-width: 1300px;
    text-align: left;
    border: solid 1px #dadde0;
    position: relative;
}

.contentsStatus {
    position: absolute;
    z-index: 2;
    top: 0px;
    right: 10px;
}
</style>